from sqlalchemy.orm import Session
from typing import Tuple
from ..models import (
    User, File, FileType, 
    FolderDepartmentPermission, FolderUserPermission
)

def get_folder_level(file: File, db: Session) -> int:
    """获取文件夹层级"""
    level = 0
    current = file
    while current.parent_id:
        level += 1
        current = db.query(File).filter(File.id == current.parent_id).first()
        if not current:
            break
    return level

def can_access_folder(folder: File, user: User, db: Session) -> Tuple[bool, bool, bool]:
    """
    检查用户是否可以访问文件夹
    返回: (can_read, can_write, can_delete)
    """
    # 管理员拥有所有权限
    if user.role.value == "admin":
        return True, True, True
    
    # 文件夹所有者拥有所有权限
    if folder.owner_id == user.id:
        return True, True, True
    
    # 检查文件夹层级限制
    folder_level = get_folder_level(folder, db)
    if folder_level <= 1:  # 第一级和第二级文件夹仅管理员可操作
        return False, False, False
    
    # 检查用户特定权限
    user_permission = db.query(FolderUserPermission).filter(
        FolderUserPermission.folder_id == folder.id,
        FolderUserPermission.user_id == user.id
    ).first()
    
    if user_permission:
        return (
            user_permission.can_read,
            user_permission.can_write,
            user_permission.can_delete
        )
    
    # 检查部门权限
    if user.department_id:
        dept_permission = db.query(FolderDepartmentPermission).filter(
            FolderDepartmentPermission.folder_id == folder.id,
            FolderDepartmentPermission.department_id == user.department_id
        ).first()
        
        if dept_permission:
            return (
                dept_permission.can_read,
                dept_permission.can_write,
                dept_permission.can_delete
            )
    
    # 检查父文件夹权限（递归）
    if folder.parent_id:
        parent = db.query(File).filter(File.id == folder.parent_id).first()
        if parent:
            return can_access_folder(parent, user, db)
    
    # 默认无权限
    return False, False, False

def can_access_file(file: File, user: User, db: Session) -> Tuple[bool, bool, bool]:
    """
    检查用户是否可以访问文件
    返回: (can_read, can_write, can_delete)
    """
    # 管理员拥有所有权限
    if user.role.value == "admin":
        return True, True, True
    
    # 文件所有者拥有所有权限
    if file.owner_id == user.id:
        return True, True, True
    
    # 根据文件共享级别检查权限
    if file.share_level == "public":
        return True, False, False  # 公开文件所有人可读
    elif file.share_level == "department" and user.department_id == file.department_id:
        return True, False, False  # 部门内可读
    elif file.share_level == "private":
        return False, False, False  # 私有文件仅所有者可访问
    
    # 检查父文件夹权限
    if file.parent_id:
        parent = db.query(File).filter(File.id == file.parent_id).first()
        if parent and parent.file_type == FileType.FOLDER:
            return can_access_folder(parent, user, db)
    
    # 默认无权限
    return False, False, False

def check_folder_operation_permission(folder_id: int, user: User, operation: str, db: Session) -> bool:
    """
    检查文件夹操作权限
    operation: 'create', 'read', 'write', 'delete'
    """
    if folder_id:
        folder = db.query(File).filter(
            File.id == folder_id,
            File.file_type == FileType.FOLDER,
            File.is_deleted == False
        ).first()
        
        if not folder:
            return False
        
        can_read, can_write, can_delete = can_access_folder(folder, user, db)
        
        if operation == "read":
            return can_read
        elif operation in ["create", "write"]:
            return can_write
        elif operation == "delete":
            return can_delete
    else:
        # 根目录操作，只有管理员可以
        return user.role.value == "admin"
    
    return False

def check_file_operation_permission(file_id: int, user: User, operation: str, db: Session) -> bool:
    """
    检查文件操作权限
    operation: 'read', 'write', 'delete'
    """
    file = db.query(File).filter(
        File.id == file_id,
        File.is_deleted == False
    ).first()
    
    if not file:
        return False
    
    can_read, can_write, can_delete = can_access_file(file, user, db)
    
    if operation == "read":
        return can_read
    elif operation == "write":
        return can_write
    elif operation == "delete":
        return can_delete
    
    return False